# -*- coding:utf-8 -*-
from flask import request, jsonify, abort
from flask_cors import CORS
from com.zzh.dao_v2.viewItemDao import ViewItemDao

from . import app

CORS(app, supports_credentials=True)


@app.route('/find_view_item', methods=['GET'])
def find_view_item():
    """
    查询 view_area
    :return:
    """
    try:
        info = ViewItemDao().findInfo()
        if info:
            return jsonify({"info": info, "message": {"code": 1, "status": "success"}})
        else:
            return jsonify({"info": [], "message": {"code": 0, "status": "No data"}})
    except Exception, e:
            return jsonify({"message": {"code": 0,  "info": str(e)}})


@app.route('/find_view_item_by_condition', methods=['POST'])
def find_view_item_by_condition():
    if not request.json:
        abort(400)
    try:
        page = request.json['page']
        pageIndex = page["pageIndex"]
        pageSize = page["pageSize"]
    except:
        return jsonify({"message": {"code": 0, "status": "请传入 pageIndex和pageSize"}})

    try:
        conditions = request.json['condition']
    except:
        return jsonify({"message": {"code": 0, "status": "未传入指定condition"}})
    try:
        multiSort = request.json['multiSort']
    except:
        return jsonify({"message": "未传入排序规则multiSort"})
    try:

        info, total = ViewItemDao().find_by_condition2(pageIndex=pageIndex, pageSize=pageSize, conditions=conditions,
                                                      multiSort=multiSort)

        if info:
            return jsonify({"total": total, "info": info, "message": {"code": 1, "status": "success"}})
        else:
            return jsonify({"info": [], "message": {"code": 0, "status": "No data"}})
    except Exception, e:
            return jsonify({"message": {"code": 0,  "info": str(e)}})


@app.route('/findItemByRandom', methods=['POST'])
def findItemByRandom():
    if not request.json:
        abort(400)
    top = request.json.get('top', 1)
    rsData = ViewItemDao().getRandomItem(top)

    if rsData:
        return jsonify({"info": rsData, "message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"info": [], "message": {"code": 0, "status": "No data"}})